package com.itboye.mengwu.app.ui.roof;

import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import test.FlowLayout;

import com.itboye.core.alert.ByAlert;
import com.itboye.core.object.BaseActivity;
import com.itboye.core.object.ResultEntity;
import com.itboye.mengwu.R;
import com.itboye.mengwu.app.ui.main.GoodsListActivity;
import com.itboye.mengwu.data.model.KeyWordQueryModel;
import com.itboye.mengwu.data.presenter.KeyWordQueryPresenter;
import com.itboye.mengwu.greendao.DaoMaster;
import com.itboye.mengwu.greendao.DaoSession;
import com.itboye.mengwu.greendao.HistoryEntity;
import com.itboye.mengwu.greendao.HistoryEntityDao;
import com.itboye.mengwu.greendao.HistoryEntityDao.Properties;

public class ActivityHomePageSearch extends BaseActivity implements Observer {

	FlowLayout tagSearchGroup;
	FlowLayout tagGroup;
	TextView txt_cancel;
	TextView txt_title;
	ImageView back;
	// img_search;
	EditText searchet;
	RelativeLayout delete_layout;
	HistoryEntity historyEntity;
	private SQLiteDatabase db;
	// 管理者
	private DaoMaster mDaoMaster;
	// 会话
	private DaoSession mDaoSession;
	// 对应的表,由java代码生成的,对数据库内相应的表操作使用此对象
	private HistoryEntityDao historyEntityDao;
	TextView[] childView;
	TextView[] childSearchView;
	KeyWordQueryModel keyWordQueryModel;
	KeyWordQueryPresenter keyWordQueryPresenter;
	ArrayList<KeyWordQueryModel> wordQueryModels = new ArrayList<KeyWordQueryModel>();
	String zuixin = "2";
	LinearLayout all;

	@Override
	public int initView() {
		// TODO Auto-generated method stub
		return R.layout.activity_homesearch;
	}

	@Override
	public void onMyCreate() {
		showProgressDialog("正在为您找热门搜索词", true);
		all.setVisibility(View.GONE);
		keyWordQueryPresenter = new KeyWordQueryPresenter(this);
		keyWordQueryPresenter.WordQuery(zuixin);

	}

	@SuppressWarnings("deprecation")
	private void doOnMyCreate() {
		// TODO Auto-generated method stub
		tagSearchGroup = (FlowLayout) findViewById(R.id.tagSearchGroup);
		childView = new TextView[wordQueryModels.size()];
		for (int i = 0; i < wordQueryModels.size(); i++) {
			tagGroup = (FlowLayout) findViewById(R.id.tagGroup);
			View view = LayoutInflater.from(ActivityHomePageSearch.this)
					.inflate(R.layout.textview, null);
			TextView textView = (TextView) view.findViewById(R.id.text);
			ImageView img_del = (ImageView) view.findViewById(R.id.img_del);
			img_del.setVisibility(View.GONE);
			tagGroup = (FlowLayout) findViewById(R.id.tagGroup);
			textView.setText(wordQueryModels.get(i).getWord() + "");
			textView.setGravity(Gravity.CENTER);
			textView.setTextColor(getResources().getColor(R.color.black));
			textView.setBackgroundDrawable(getResources().getDrawable(
					R.drawable.biaoqianshape2));
			textView.setTag(i);
			childView[i] = textView;
			childView[i].setTag(i);
			android.widget.RelativeLayout.LayoutParams lP = new android.widget.RelativeLayout.LayoutParams(
					android.widget.RelativeLayout.LayoutParams.WRAP_CONTENT,
					android.widget.RelativeLayout.LayoutParams.WRAP_CONTENT);
			lP.setMargins(10, 10, 10, 10);
			tagGroup.addView(view, lP);
			try {
				all.setVisibility(View.VISIBLE);
				closeProgressDialog();
			} catch (Exception e) {
				// TODO: handle exception
			}
			childView[i].setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					searchet.setText(childView[Integer.parseInt(v.getTag() + "")]
							.getText().toString());

				}
			});
		}

		initDatabase();
		delete_layout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				historyEntity = new HistoryEntity();
				historyEntityDao.deleteAll();
				getTagSearchGroupInFo();
			}
		});
		txt_cancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				String text = searchet.getText() + "";

				Boolean flag = false;
				int key = 0, i = 0;
				;
				if (!"".equals(text) & text != null) {
					historyEntity = new HistoryEntity();
					historyEntity.setSearchString(searchet.getText() + "");

					List<HistoryEntity> allList = historyEntityDao
							.queryBuilder().list();
					for (HistoryEntity historyEntity : allList) {

						if (historyEntity.getSearchString().trim()
								.equals((searchet.getText() + "").trim())) {
							flag = true;
							key = i;
							break;
						}
						i++;

					}
					if (flag) {
						historyEntityDao.delete(allList.get(key));
						historyEntityDao.insert(historyEntity);
						Intent intent2 = new Intent(
								ActivityHomePageSearch.this,
								GoodsListActivity.class);
						intent2.putExtra("goodsname", searchet.getText() + "");
						startActivity(intent2);
						finish();

					} else {
						historyEntityDao.insert(historyEntity);
						Intent intent = new Intent(ActivityHomePageSearch.this,
								GoodsListActivity.class);
						intent.putExtra("goodsname", searchet.getText() + "");
						startActivity(intent);
						finish();
					}

				} else {
					ByAlert.alert("输入不能为空，请重新输入！");
				}
			}
		});
		back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});

	}

	private void initDatabase() {
		DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this,
				"daodemo.db", null);
		db = helper.getWritableDatabase();
		mDaoMaster = new DaoMaster(db);
		mDaoSession = mDaoMaster.newSession();
		historyEntityDao = mDaoSession.getHistoryEntityDao();
		getTagSearchGroupInFo();

		// 一条一条加
		// historyEntity = new HistoryEntity();
		// historyEntity.setSearchString();
		// historyEntityDao.insert(historyEntity);
		// List<HistoryEntity> historyEntities = new ArrayList<HistoryEntity>();

	}

	@SuppressWarnings("deprecation")
	private void getTagSearchGroupInFo() {

		tagSearchGroup.removeAllViews();
		int x = 0;
		List<HistoryEntity> historyList = historyEntityDao.queryBuilder()
				.orderDesc(Properties.Id).list();
		childSearchView = new TextView[historyList.size()];
		for (HistoryEntity historyEntity : historyList) {
			// Log.d("TAGGG", historyEntity.getSearchString());
			TextView textView = new TextView(this);
			textView.setText(historyEntity.getSearchString());
			textView.setGravity(Gravity.CENTER);
			textView.setBackgroundDrawable(getResources().getDrawable(
					R.drawable.biaoqianshape));
			textView.setTag(x);
			childSearchView[x] = textView;
			android.widget.RelativeLayout.LayoutParams lP = new android.widget.RelativeLayout.LayoutParams(
					android.widget.RelativeLayout.LayoutParams.WRAP_CONTENT,
					android.widget.RelativeLayout.LayoutParams.WRAP_CONTENT);
			lP.setMargins(10, 10, 10, 10);
			childSearchView[x].setTag(x);
			tagSearchGroup.addView(childSearchView[x], lP);

			childSearchView[x].setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					searchet.setText(childSearchView[Integer.parseInt(v
							.getTag() + "")].getText());
				}
			});
			x++;
		}

	}

	@SuppressWarnings("unchecked")
	@Override
	public void update(Observable observable, Object data) {
		// TODO Auto-generated method stub
		ResultEntity entity = handlerError(data);
		if (entity.getEventType() == KeyWordQueryPresenter.Query_success) {
			wordQueryModels.clear();
			wordQueryModels.addAll((ArrayList<KeyWordQueryModel>) entity
					.getData());
		}
		doOnMyCreate();

	}

}
